//
//  PeopleViewController.m
//

#import "PeopleViewController.h"
#import "ImageButtonView.h"
#import "AppDelegate.h"
#import "User.h"
#import "PeopleProfileViewController.h"
#import "PeopleFilterViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "Extensions.h"

@implementation NSDictionary (Extension)

- (id)newObjectForKey:(id)aKey
{
    id rez = [self objectForKey:aKey];
    
    return ([rez isKindOfClass:[NSNull class]] ? nil : rez);
}
@end

@implementation UIButtonAvatar

@synthesize userInfo = _userInfo;

- (void)makeBoderAndShadow
{
    self.clipsToBounds = NO;
    self.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.layer.borderWidth = 2;
    self.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.layer.shadowRadius = 1;
    self.layer.shadowOpacity = 0.45;
    self.layer.shadowOffset = CGSizeMake(0, 0);
}

@end

@implementation PeopleViewController

@synthesize lbl1,lbl2,tblView,myCell;
@synthesize currentFilter = _currentFilter;
@synthesize lastFilter = _lastFilter;
@synthesize locationManager;
//@synthesize bestEffortAtLocation;
@synthesize isFav;
@synthesize peopleView = _peopleView;
@synthesize delegate;

-(void)applyAppearance 
{
    [self setLeftButtonImageActiveName:nil inactiveName:@"back-button" target:self action:@selector(backPressed)];
    [self setRightButtonImageActiveName:nil inactiveName:@"filter-button" target:self action:@selector(editPressed)];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]]; 
}

-(void) backPressed 
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void) editPressed 
{
    PeopleFilterViewController *pfVC = [[PeopleFilterViewController alloc]initWithNibName:@"PeopleFilterViewController" bundle:nil];
    pfVC.delegate = self;
    pfVC.filterStr = self.lastFilter;
    [self.navigationController pushViewController:pfVC animated:YES];
    [pfVC release];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Private Method

- (void)showPeople:(UIButtonAvatar*)sender 
{   
    if (self.peopleView == BlockMode) {
        [self.delegate didSelectedPerson:(NSDictionary *)sender.userInfo];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        NSLog(@"Selected_User = %@",sender.userInfo);
        PeopleProfileViewController *ppvc = [[PeopleProfileViewController alloc] initWithNibName:@"PeopleProfileViewController" 
                                                                                              bundle:nil];
        ppvc.user_info = (NSDictionary *)sender.userInfo;   
        [self.navigationController pushViewController:ppvc animated:YES];
        [ppvc release];
    }
}

- (void)canReloadAvatarForCell:(UITableViewCell*)cell andIndexPath:(NSIndexPath*)indexPath
{      
    UIButtonAvatar *img1 = (UIButtonAvatar *)[cell viewWithTag:1];
    UIButtonAvatar *img2 = (UIButtonAvatar *)[cell viewWithTag:2];
    UIButtonAvatar *img3 = (UIButtonAvatar *)[cell viewWithTag:3];
    UIButtonAvatar *img4 = (UIButtonAvatar *)[cell viewWithTag:4];
    UILabel *name1 = (UILabel *)[cell viewWithTag:5];
    UILabel *name2 = (UILabel *)[cell viewWithTag:6];
    UILabel *name3 = (UILabel *)[cell viewWithTag:7];
    UILabel *name4 = (UILabel *)[cell viewWithTag:8];
    name1.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
    name2.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
    name3.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
    name4.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];

    
    
    [img1 makeBoderAndShadow];
    [img2 makeBoderAndShadow];
    [img3 makeBoderAndShadow];
    [img4 makeBoderAndShadow];    
    
    NSDictionary *aPerson = nil;
    UIImage *avatar = nil;
    UIImage *onlineDimImage = [UIImage imageNamed:@"people-odim-bg"];
    UIImage *onlineImage = [UIImage imageNamed:@"people-online-bg"];
    
    if (indexPath.section == 0) {
        
        NSInteger begin = 4 * indexPath.row;
        
        if (begin < [listNearbyPeople count]) {
            aPerson = [listNearbyPeople objectAtIndex:begin]; 
            avatar = [aPerson objectForKey:@"avatar"] ? [aPerson objectForKey:@"avatar"] : [UIImage imageNamed:@"photo-frame"];
            img1.hidden = NO;
            
            [img1 setBackgroundImage:avatar forState:UIControlStateNormal];            
            [img1 addTarget:self action:@selector(showPeople:) forControlEvents:UIControlEventTouchUpInside]; 
            [img1 setUserInfo:aPerson];
            [img1 setImage:([[aPerson objectForKey:@"online_status"] integerValue] == 1 ? onlineDimImage : nil) forState:UIControlStateNormal];
            [cell titleTextWithTag:11].hidden = ([[aPerson objectForKey:@"online_status"] integerValue] == 0);
            [cell titleTextWithTag:11].text = [JGoUtility distanceString:[[aPerson objectForKey:@"distance"] stringValue]];
            name1.hidden = NO;
            name1.text = [aPerson objectForKey:@"name"];
        }
        else {
            name1.hidden = YES;
            img1.hidden = YES;
            [cell titleTextWithTag:11].hidden = YES;
        }
        
        if (begin + 1 < [listNearbyPeople count]) {
            aPerson = [listNearbyPeople objectAtIndex:begin + 1];            
            img2.hidden = NO;            
            avatar = [aPerson objectForKey:@"avatar"] ? [aPerson objectForKey:@"avatar"] : [UIImage imageNamed:@"photo-frame"];
            
            [img2 setBackgroundImage:avatar forState:UIControlStateNormal];     
            [img2 addTarget:self action:@selector(showPeople:) forControlEvents:UIControlEventTouchUpInside];
            [img2 setUserInfo:aPerson];
            [img2 setImage:([[aPerson objectForKey:@"online_status"] integerValue] == 1 ? onlineDimImage : nil) forState:UIControlStateNormal];
            [cell titleTextWithTag:21].hidden = ([[aPerson objectForKey:@"online_status"] integerValue] == 0);
            [cell titleTextWithTag:21].text = [JGoUtility distanceString:[[aPerson objectForKey:@"distance"] stringValue]];
            name2.text = [aPerson objectForKey:@"name"];
            name2.hidden = NO;
        }
        else {
            img2.hidden = YES;
            name2.hidden = YES;
            [cell titleTextWithTag:21].hidden = YES;
            
        }
        
        if (begin + 2 < [listNearbyPeople count]) {
            aPerson = [listNearbyPeople objectAtIndex:begin + 2];            
            img3.hidden = NO;
            avatar = [aPerson objectForKey:@"avatar"] ? [aPerson objectForKey:@"avatar"] : [UIImage imageNamed:@"photo-frame"];
            
            [img3 setBackgroundImage:avatar forState:UIControlStateNormal];                       
            [img3 addTarget:self action:@selector(showPeople:) forControlEvents:UIControlEventTouchUpInside];
            [img3 setUserInfo:aPerson];
            [img3 setImage:([[aPerson objectForKey:@"online_status"] integerValue] == 1 ? onlineDimImage : nil) forState:UIControlStateNormal];
            [cell titleTextWithTag:31].hidden = ([[aPerson objectForKey:@"online_status"] integerValue] == 0);
            [cell titleTextWithTag:31].text = [JGoUtility distanceString:[[aPerson objectForKey:@"distance"] stringValue]];
            name3.text = [aPerson objectForKey:@"name"];
            name3.hidden = NO;
        }
        else {
            img3.hidden = YES;
            name3.hidden = YES;
            [cell titleTextWithTag:31].hidden = YES;
        }
        
        if (begin + 3 < [listNearbyPeople count]) {
            aPerson = [listNearbyPeople objectAtIndex:begin + 3];            
            img4.hidden = NO;
            avatar = [aPerson objectForKey:@"avatar"] ? [aPerson objectForKey:@"avatar"] : [UIImage imageNamed:@"photo-frame"];
            
            [img4 setBackgroundImage:avatar forState:UIControlStateNormal];                       
            [img4 addTarget:self action:@selector(showPeople:) forControlEvents:UIControlEventTouchUpInside];
            [img4 setUserInfo:aPerson];
            [img4 setImage:([[aPerson objectForKey:@"online_status"] integerValue] == 1 ? onlineDimImage : nil) forState:UIControlStateNormal];
            [cell titleTextWithTag:41].hidden = ([[aPerson objectForKey:@"online_status"] integerValue] == 0);
            [cell titleTextWithTag:41].text = [JGoUtility distanceString:[[aPerson objectForKey:@"distance"] stringValue]];
            name4.text = [aPerson objectForKey:@"name"];
            name4.hidden = NO;
        }
        else {
            img4.hidden = YES;
            name4.hidden = YES;
            [cell titleTextWithTag:41].hidden = YES;
        }
    }
    else {
        NSInteger begin = 4 * indexPath.row;
        
        if (begin < [listCityPeople count]) {
            aPerson = [listCityPeople objectAtIndex:begin];
            img1.hidden = NO;
            avatar = [aPerson objectForKey:@"avatar"] ? [aPerson objectForKey:@"avatar"] : [UIImage imageNamed:@"photo-frame"];
            
            [img1 setBackgroundImage:avatar forState:UIControlStateNormal];                       
            [img1 addTarget:self action:@selector(showPeople:) forControlEvents:UIControlEventTouchUpInside];
            [img1 setUserInfo:aPerson];
            [img1 setImage:([[aPerson objectForKey:@"online_status"] integerValue] == 1 ? onlineImage : nil) forState:UIControlStateNormal]; 
            [cell titleTextWithTag:11].hidden = YES;
            name1.text = [aPerson objectForKey:@"name"];
            name1.hidden = NO;
        }
        else {
            img1.hidden = YES;
            name1.hidden = YES;
        }
        
        if (begin + 1 < [listCityPeople count]) {
            aPerson = [listCityPeople objectAtIndex:begin + 1];            
            img2.hidden = NO;    
            avatar = [aPerson objectForKey:@"avatar"] ? [aPerson objectForKey:@"avatar"] : [UIImage imageNamed:@"photo-frame"];
            
            [img2 setBackgroundImage:avatar forState:UIControlStateNormal];            
            [img2 addTarget:self action:@selector(showPeople:) forControlEvents:UIControlEventTouchUpInside];
            [img2 setUserInfo:aPerson];
            [img2 setImage:([[aPerson objectForKey:@"online_status"] integerValue] == 1 ? onlineImage : nil) forState:UIControlStateNormal];
            [cell titleTextWithTag:21].hidden = YES;
            name2.text = [aPerson objectForKey:@"name"];
            name2.hidden = NO;
        }
        else {
            img2.hidden = YES;
            name2.hidden = YES;
        }
        
        if (begin + 2 < [listCityPeople count]) {
            aPerson = [listCityPeople objectAtIndex:begin + 2];            
            img3.hidden = NO;
            avatar = [aPerson objectForKey:@"avatar"] ? [aPerson objectForKey:@"avatar"] : [UIImage imageNamed:@"photo-frame"];
            
            [img3 setBackgroundImage:avatar forState:UIControlStateNormal];            
            [img3 addTarget:self action:@selector(showPeople:) forControlEvents:UIControlEventTouchUpInside];
            [img3 setUserInfo:aPerson];
            [img3 setImage:([[aPerson objectForKey:@"online_status"] integerValue] == 1 ? onlineImage : nil) forState:UIControlStateNormal];   
            [cell titleTextWithTag:31].hidden = YES;
            name3.text = [aPerson objectForKey:@"name"];
            name3.hidden = NO;
        }
        else {
            img3.hidden = YES;
            name3.hidden = YES;
        }
        
        if (begin + 3 < [listCityPeople count]) {
            aPerson = [listCityPeople objectAtIndex:begin + 3];            
            img4.hidden = NO;
            avatar = [aPerson objectForKey:@"avatar"] ? [aPerson objectForKey:@"avatar"] : [UIImage imageNamed:@"photo-frame"];
            
            [img4 setBackgroundImage:avatar forState:UIControlStateNormal];           
            [img4 addTarget:self action:@selector(showPeople:) forControlEvents:UIControlEventTouchUpInside];
            [img4 setUserInfo:aPerson];
            [img4 setImage:([[aPerson objectForKey:@"online_status"] integerValue] == 1 ? onlineImage : nil) forState:UIControlStateNormal];
            [cell titleTextWithTag:41].hidden = YES;
            name4.text = [aPerson objectForKey:@"name"];
            name4.hidden = NO;
        }
        else {
            img4.hidden = YES;
            name4.hidden = YES;
        }        
    }    
}

- (void)reviewPeopleData
{
    for (NSDictionary *aPeople in listCityPeople) {
        NSString *valueString = [aPeople objectForKey:@"dob"];
        id object = [JGoUtility dateFromString1:valueString];
        [aPeople setValue:object forKey:@"dob"];
        
        valueString = [aPeople objectForKey:@"modules"];
        object = [valueString componentsSeparatedByString:@";"];
        [aPeople setValue:object forKey:@"modules"];
    }
    
    for (NSDictionary *aPeople in listNearbyPeople) {
        NSString *valueString = [aPeople objectForKey:@"dob"];
        id object = [JGoUtility dateFromString1:valueString];
        [aPeople setValue:object forKey:@"dob"];
        
        valueString = [aPeople objectForKey:@"modules"];
        object = [valueString componentsSeparatedByString:@";"];
        [aPeople setValue:object forKey:@"modules"];
    }
}

- (void)asyncLoadAvatar
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    
    dispatch_async(queue, ^{
        
        for (NSDictionary *aPerson in listNearbyPeople) {
            NSError *error = nil;
            UIImage * personAvatar = [JGoAPI downloadAvatar:[aPerson objectForKey:@"thumb"] error:&error];
            
            if (error == nil) {
                [aPerson setValue:personAvatar forKey:@"avatar"];
                [tblView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
            }
            else {
                [aPerson setValue:[UIImage imageNamed:@"photo-frame"] forKey:@"avatar"];
            }
        }    
        
        for (NSDictionary *aPerson in listCityPeople) {
            NSError *error = nil;
            UIImage * personAvatar = [JGoAPI downloadAvatar:[aPerson objectForKey:@"thumb"] error:&error];
            
            if (error == nil) {
                [aPerson setValue:personAvatar forKey:@"avatar"];
                [tblView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
            }
            else {
                [aPerson setValue:[UIImage imageNamed:@"photo-frame"] forKey:@"avatar"];
            }
        }        
    });    

}

- (NSString*)arrayStringPeople
{
    NSString *stringPeople = nil;
    
    for (NSDictionary *aPerson in listNearbyPeople) {
        
        if (stringPeople == nil) {
            stringPeople = [aPerson objectForKey:@"user_id"];
        }
        else {
            stringPeople = [NSString stringWithFormat:@"%@;%@",stringPeople,[aPerson objectForKey:@"user_id"]];
        }        
    }

    for (NSDictionary *aPerson in listCityPeople) {
        
        if (stringPeople == nil) {
            stringPeople = [aPerson objectForKey:@"user_id"];
        }
        else {
            stringPeople = [NSString stringWithFormat:@"%@;%@",stringPeople,[aPerson objectForKey:@"user_id"]];
        }        
    }
    
    return stringPeople;
}

- (void)asyncLoadOnline
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    
    dispatch_async(queue, ^{
        
        NSString *userIds = [self arrayStringPeople];
        onlineUsers = [JGoAPI getOnlineWithUserIds:userIds error:nil];
        [tblView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
    });
}

-(void)getAddressFromLatLon
{
    CLGeocoder * geoCoder = [[[CLGeocoder alloc] init]autorelease];

    [geoCoder reverseGeocodeLocation: locationManager.location completionHandler:
     ^(NSArray *placemarks, NSError *error) {
         
         //Get nearby address
         CLPlacemark *placemark = [placemarks objectAtIndex:0];
         cityName = [placemark locality];
         NSLog(@"I am currently at %@",cityName);
         //String to hold address
         //NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
         
         //Print the location to console
         //NSLog(@"I am currently at %@",locatedAt);
         
         //Set the label text to current location
        // [locationLabel setText:locatedAt];
         
     }];
}

#pragma mark - View lifecycle


- (void)viewDidLoad 
{
    [super viewDidLoad];
    lbl1.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
    lbl2.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
    
    [self.tblView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.tblView.backgroundColor = [UIColor clearColor];
    self.tblView.opaque = NO;
    self.tblView.backgroundView = nil;
    self.tblView.separatorColor = [UIColor clearColor];  
    /*
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notificationChangedFilter:) 
                                                 name:JGO_PEOPLE_CHANGED_FILTER object:nil];
    */
    /*
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notificationDidUpdateLocation:)
                                                 name:JGO_APP_DID_UPDATE_LOCATION object:nil];
    */
    [self getPeopleWithLocation];
    //[[NSNotificationCenter defaultCenter] postNotificationName:JGO_APP_UPDATE_LOCATION object:nil];
    
    [self setCurrentFilter:@"All"];
    [self setLastFilter:@"All"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self applyAppearance];
    
    if (isFav) {
        [self setTitle:@"Favorites"];
    } 
    else {
       [self setTitle:@"People"]; 
    }    
    
    [super viewWillAppear:animated];    
}
-(void)dealloc
{
    [self stopUpdatingLocation];
    [tblView release];
    [myCell release];
    [lbl1 release];
    [lbl2 release];
    [locationManager release];
    //[bestEffortAtLocation release];
    [super dealloc];
}
#pragma mark - Notification

- (void)notificationChangedFilter:(NSNotification*)notification
{
    NSString *newFilter = [notification.userInfo objectForKey:@"value"];
    [self setCurrentFilter:newFilter];
}

- (void)notificationDidUpdateLocation:(NSNotification*)notification
{
    if (listCityPeople == nil && listNearbyPeople == nil) {
        [JGoUtility showProgressInView:self.view 
                                target:self title:@"Loading People..." 
                              selector:@selector(delayLoadPeople:)];    
    }
}

#pragma mark - TableView Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{        
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        int result = [listNearbyPeople count] / 4;
        int redundancy = [listNearbyPeople count] % 4;
        
        int numberOfRows = (redundancy == 0) ? result : (result + 1);
        return numberOfRows;
    }
    else {
        int result = [listCityPeople count] / 4;
        int redundancy = [listCityPeople count] % 4;
        
        int numberOfRows = (redundancy == 0) ? result : (result + 1);
        return numberOfRows;
    }       
}

 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
 {
     return 44;
 }
 
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
        switch (section) {
                
            case 0: {
                UILabel *lblText = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
                lblText.text = @"  Nearby";
                lblText.font = [UIFont systemFontOfSize:14];
                lblText.backgroundColor = [UIColor clearColor];
                [lblText sizeToFit];
                return [lblText autorelease];
                break;
            }
            case 1: {
                UILabel *lblText = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
                if (isFav) {
                    if (cityName != nil) {
                        lblText.text = cityName;
                    }else {
                    lblText.text = @"  All";
                    }
                }
                else
                {
                    if (cityName != nil) {
                        lblText.text = cityName;
                    }else {
                        lblText.text = @"  City";
                    }
                    
                }
                
                lblText.font = [UIFont systemFontOfSize:14];
                lblText.backgroundColor = [UIColor clearColor];
                [lblText sizeToFit];
                return [lblText autorelease];
                break;
                
            }
        }
            
    return nil;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"PeopleCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"PeopleCell" owner:self options:nil];
        cell = myCell;
        self.myCell = nil;
    }
    
    [self canReloadAvatarForCell:cell andIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
    
}

#pragma mark - delay Method

- (void)delayLoadPeople:(MBProgressHUD*)progress
{
    NSError *error = nil;
    NSString *lat ;//= [JGoUtility sharedLatitude];
    NSString *lon ;//= [JGoUtility sharedLongitude];
    //bestEffortAtLocation = [locationManager location];
    float currentLatitude = [[locationManager location]coordinate].latitude;
    lat = [NSString stringWithFormat:@"%f",currentLatitude];
    float currentLongitude = [[locationManager location]coordinate].longitude;
    lon = [NSString stringWithFormat:@"%f",currentLongitude];
    NSLog(@"Current_Filter = %@",self.currentFilter);
    NSLog(@"LAT= %@ - LONG=%@",lat,lon);
    
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSArray *nearbyPeople;
    
    if (isFav) {
        nearbyPeople = [JGoAPI getPeopleWithUserId:userId
                                                   searchBy:@"nearBy"
                                                      isFav:YES 
                                                     filter:([self.currentFilter isEqualToString:@"All"] ? @"":self.currentFilter)
                                                        lat:lat
                                                        lon:lon
                                                      error:&error];
    }
    else {
        
        nearbyPeople = [JGoAPI getPeopleWithUserId:userId
                                               searchBy:@"nearBy"
                                                  isFav:NO 
                                                 filter:([self.currentFilter isEqualToString:@"All"] ? @"":self.currentFilter)
                                                    lat:lat
                                                    lon:lon
                                                  error:&error];
    }
    
    if (error) {        
        LOG(@"%@", [error localizedDescription]);
    }
    else {
        listNearbyPeople = (id)[nearbyPeople retain];
        NSArray *cityPeople;
        if (isFav) {
            cityPeople = [JGoAPI getPeopleWithUserId:userId
                                                     searchBy:@"city"
                                                        isFav:YES 
                                                       filter:([self.currentFilter isEqualToString:@"All"] ? @"":self.currentFilter)
                                                          lat:lat
                                                          lon:lon
                                                        error:&error];
        }else {
            cityPeople = [JGoAPI getPeopleWithUserId:userId
                                                     searchBy:@"city"
                                                        isFav:NO 
                                                       filter:([self.currentFilter isEqualToString:@"All"] ? @"":self.currentFilter)
                                                          lat:lat
                                                          lon:lon
                                                        error:&error];
        }
        
        
        if (error) {
            LOG(@"%@", [error localizedDescription]);
        }
        else {
            listCityPeople = (id)[cityPeople retain];
        }
    }
     
    [self reviewPeopleData];
    [tblView reloadData];
    [self asyncLoadAvatar];
    
    [progress hide:YES];
}


- (void)setupViewController:(PeopleFilterViewController *)controller didFinishSetupWithInfo:(NSString *)filterString
{
    NSLog(@"FilterString = %@",filterString);
    self.currentFilter = filterString;
    
    if (![self.lastFilter isEqualToString:self.currentFilter]) {
        /*[JGoUtility showProgressInView:self.view
                                target:self title:@"Reloading People..." 
                              selector:@selector(delayLoadPeople:)];
         */
        self.lastFilter = filterString;
        [self getPeopleWithLocation];
    }
    
    
}

#pragma mark Location Manager Interactions

- (void)stopUpdatingLocation {
    //self.stateString = state;
    //[self.tblView reloadData];
    [locationManager stopUpdatingLocation];
    locationManager.delegate = nil;
    
}
- (void)getPeopleWithLocation
{
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    self.locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    //self.locationManager.desiredAccuracy = [[NSNumber numberWithDouble:kCLLocationAccuracyNearestTenMeters]doubleValue];
    [self.locationManager startUpdatingLocation];
    [self getAddressFromLatLon];
    [JGoUtility showProgressInView:self.view
                            target:self title:@"Loading People..."
                          selector:@selector(delayLoadPeople:)];
    //[self performSelector:@selector(stopUpdatingLocation) withObject:nil afterDelay:30];
}

/*
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 5.0) return;
    if (newLocation.horizontalAccuracy < 0) return;
    if (bestEffortAtLocation == nil || bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy || ![self.lastFilter isEqualToString:self.currentFilter])
    {
        self.bestEffortAtLocation = newLocation;
        
        if (newLocation.horizontalAccuracy <= locationManager.desiredAccuracy) {
        
        [self stopUpdatingLocation];
        [JGoUtility showProgressInView:self.view
                                    target:self title:@"Loading People..."
                                  selector:@selector(delayLoadPeople:)];
            self.lastFilter = self.currentFilter;
        //[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpdatingLocation) object:nil];
        }
        
    }
    
    //[self.tblView reloadData];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    if ([error code] != kCLErrorLocationUnknown) {
        [self stopUpdatingLocation];
    }
    [JGoUtility showAlert:[error localizedDescription]];
}

*/
@end
